package com.miyu.book.utils.bookUtils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.miyu.book.dao.bookMagic.BookMagicDao;
import com.miyu.book.utils.ehcache.EhcacheUtil;
import com.miyu.book.utils.magic.GetBeanUtil;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

public class saveThead implements Callable<JSONObject> {
    private JSONObject param;
    private JSONObject data;
    BookMagicDao dao = (BookMagicDao) GetBeanUtil.getBeanByClass(BookMagicDao.class);

    public  saveThead(JSONObject param,JSONObject data){
        this.param=param;
        this.data=data;

    }
    @Override
    public JSONObject call() throws Exception {
        String book = param.getString("ruleBookList");//小说明细表
        //增加分表 取出分表表名

        String chTable = param.getString("ruleChapterList");//小说章节
        chTable = chTable+"_"+ BookCommutils.getTable();
        if (!data.isEmpty()){
            JSONObject bookInfo = data.getJSONObject("bookInfo");
            StringBuffer sql = new StringBuffer();
            sql.append(" insert into ") .append(book).append(" (book_id,rule_id,book_source,book_name,book_chapter_source,book_author,book_kind,book_state,book_cover,book_duce,book_last_chapter");
            sql.append(" ,book_last_chapter_url,book_last_chapter_date) ");
            sql.append(" values (");
            sql.append("'").append(bookInfo.getString("bookId")).append("',");
            sql.append("'").append(bookInfo.getString("ruleId")).append("',");
            sql.append("'").append(bookInfo.getString("bookUrl")).append("',");
            sql.append("'").append(bookInfo.getString("bookName")).append("',");
            sql.append("'").append(chTable).append("',");
            if (bookInfo.containsKey("bookAuthor"))
                sql.append("'").append(bookInfo.getString("bookAuthor")).append("',");
            else
                sql.append(" null,");
            if (bookInfo.containsKey("bookKind"))
                sql.append("'").append(bookInfo.getString("bookKind")).append("',");
            else
                sql.append(" null,");

            if (bookInfo.containsKey("bookState"))
                sql.append("'").append(bookInfo.getString("bookState")).append("',");
            else
                sql.append(" null,");
            if (bookInfo.containsKey("bookCover"))
                sql.append("'").append(bookInfo.getString("bookCover")).append("',");
            else
                sql.append(" null,");
            if (bookInfo.containsKey("bookDuce"))
                sql.append("'").append(bookInfo.getString("bookDuce")).append("',");
            else
                sql.append(" null,");
            if (bookInfo.containsKey("bookLastChapter"))
                sql.append("'").append(bookInfo.getString("bookLastChapter")).append("',");
            else
                sql.append(" null,");
            if (bookInfo.containsKey("bookLastChapterUrl"))
                sql.append("'").append(bookInfo.getString("bookLastChapterUrl")).append("',");
            else
                sql.append(" null,");
            if (bookInfo.containsKey("bookLastChapterDate"))
                sql.append("'").append(bookInfo.getString("bookLastChapterDate")).append("')");
            else
                sql.append(" null)");

           // System.out.println("执行sql："+sql);
            dao.doExecute(sql.toString());//保存小说明细

            //再次处理小说章节
            //调用递归处理章节
            JSONArray chapterList = data.getJSONArray("chapterInfo");
            //牵涉到初始化时章节过多暂时不解析章节内容
            saveInitChapter(chapterList,chTable,bookInfo.getString("bookId")) ;
         //   saveChapter(chapterList,chTable);

        }
        return null;
    }

    private void saveInitChapter(JSONArray chapterList, String chTable,String bookId) {

        List<String> sqlList = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        for (int i = 0; i < chapterList.size(); i++) {
            sql.setLength(0);
            sql.append(" insert into ").append(chTable).append(" ( chapter_id,book_id,chapter_source,chapter_num,chapter_name,chapter_context)");
            sql.append(" values (");
            sql.append("'").append(chapterList.getJSONObject(i).getString("chapterId")).append("',");
            sql.append("'").append(chapterList.getJSONObject(i).getString("bookId")).append("',");
            sql.append("'").append(chapterList.getJSONObject(i).getString("chapterUrl")).append("',");
            sql.append("'").append(chapterList.getJSONObject(i).getString("num")).append("',");
            sql.append("'").append(chapterList.getJSONObject(i).getString("chapterName")).append("',");
            sql.append("'").append(chapterList.getJSONObject(i).getString("chapterContext")).append("')");
            sqlList.add(sql.toString());
        }
        if (sqlList.size()>0){
            dao.doExecuteBatch(sqlList);
            //移除当前小说缓存 节省缓内存
            EhcacheUtil.getInstance().remove("bookEhcache",bookId);
        }

    }


    /**
     * 递归处理章节问题
     * @param chapterList
     */
    public void saveChapter(JSONArray chapterList,String chTable){

        if(chapterList.size()>0){
            String chapter =chTable;//小说章节表
            StringBuffer sql = new StringBuffer();
            JSONObject ch = chapterList.getJSONObject(0);
            // 调用规则解析当前章节 如果解析成功则保存值数据库 否则再次进行解析
            //暂时使用单线程解析 多线程情况下会出现解析页面失败的问题 如果解析失败 再次加入到数组中等待解析
            // 每个页面解析10次 如果10次 还没有解析出来数据 则放弃解析 但数据还要保存 防止无限死循环出现
            //解析成功进行保存 移除缓存章节数据 节约硬盘 失败记录重试次数 加入
//            String ruleId = param.getString("ruleId") ;

            String id = BookCommutils.getUUID();

            JSONObject reset = JSONObject.parseObject(param.getString("ruleSet"));
            JSONObject req = new JSONObject();
            List<String> set = new ArrayList<>();
            set.add("chapterContext");
            JSONObject cond = new JSONObject();
            cond.put("key",id);
            cond.put("num",set);
            req.put("ruleSet",reset);
            req.put("cond",cond);
            req.put("thread",1);
            req.put("param",ch);//附加参数
            req.put("url",ch.getString("chapterUrl"));

            RuleJXData.RuleJXDataPage(req);

          JSONObject   bs = (JSONObject) EhcacheUtil.getInstance().get("bookEhcache",id);
            EhcacheUtil.getInstance().remove("bookEhcache",id);
          if(bs.getString("chapterContext").length()>0){
              sql.append(" insert into ").append(chapter).append(" ( chapter_id,book_id,chapter_source,chapter_num,chapter_name,chapter_context)");
              sql.append(" values (");
              sql.append("'").append(bs.getString("chapterId")).append("',");
              sql.append("'").append(bs.getString("bookId")).append("',");
              sql.append("'").append(bs.getString("chapterUrl")).append("',");
              sql.append("'").append(bs.getString("num")).append("',");
              sql.append("'").append(bs.getString("chapterName")).append("',");
              sql.append("'").append(bs.getString("chapterContext")).append("')");
              //System.out.println("执行sql："+sql);
              dao.doExecute(sql.toString());
              chapterList.remove(0);
              saveChapter(chapterList,chTable);

          }else{
            //  int retry = 1;
              if(ch.containsKey("retry")){
                  if(ch.getInteger("retry")>10){
                      sql.append(" insert into ").append(chapter).append(" ( chapter_id,book_id,chapter_source,chapter_num,chapter_name,chapter_context)");
                      sql.append(" values (");
                      sql.append("'").append(ch.getString("chapterId")).append("',");
                      sql.append("'").append(ch.getString("bookId")).append("',");
                      sql.append("'").append(ch.getString("chapterUrl")).append("',");
                      sql.append("'").append(ch.getString("num")).append("',");
                      sql.append("'").append(ch.getString("chapterName")).append("',");
                      sql.append("null)");
                     // System.out.println("执行sql："+sql);
                      dao.doExecute(sql.toString());
                  }else{
                      ch.put("retry",ch.getInteger("retry")+1);
                  }
              }else{
                  ch.put("retry",1);
                  chapterList.add(ch);
              }
              chapterList.remove(0);
              saveChapter(chapterList,chTable);
          }
        }else {
            return;
        }

    }
}
